#
# Copyright (c) 2011, EPFL (Ecole Politechnique Federale de Lausanne)
# All rights reserved.
#
# Created by Marco Canini, Daniele Venzano, Dejan Kostic, Jennifer Rexford
# Contributed to this file: Peter Peresini
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   -  Redistributions of source code must retain the above copyright notice,
#      this list of conditions and the following disclaimer.
#   -  Redistributions in binary form must reproduce the above copyright notice,
#      this list of conditions and the following disclaimer in the documentation
#      and/or other materials provided with the distribution.
#   -  Neither the names of the contributors, nor their associated universities or
#      organizations may be used to endorse or promote products derived from this
#      software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

from invariants.invariant_dispatcher import testPoint

from lib.of_packet_out_message import PacketOutMessage
from lib.of_modify_state_message import ModifyStateMessage
from lib.of_flow_table_modification_message import FlowTableModificationMessage

from nox.lib import openflow

class Context:

	def __init__(self, model):
		self.cnt = None
		self.model = model

	def setController(self, cnt):
		self.cnt = cnt

# X-CHANGE
	def send_openflow(self, dp_id, buffer_id, packet, actions, inport, wait_bit = False, next_entry_attr = {}, next_entry_vn = -1):

		#sw = Topology.getSwitchById(dp_id)
		sw = self.cnt.in_connections[dp_id][0]
		if buffer_id == None: # Packet generated by the controller
			packet.packet_id = self.model.genPacketID("ctrl")
			testPoint("packet_sent", sender=self.cnt, receiver=sw, packet=packet)
# X-CHANGE
		cmd = PacketOutMessage(buffer_id, packet, actions, inport, wait_bit, next_entry_attr, next_entry_vn)
		
		sw.enqueueCommand(cmd)

# X-CHANGE
	def install_datapath_flow(self, dp_id, attrs, idle_timeout, hard_timeout, actions, buffer_id=None,
			priority=openflow.OFP_DEFAULT_PRIORITY, inport=None, packet=None, vn = -1, wait_bit = False, next_entry_attr = {}, next_entry_vn = -1):
		assert vn != None
		add_args = (idle_timeout, actions, buffer_id)
		self.send_flow_command(dp_id, openflow.OFPFC_ADD, attrs, priority, add_args, hard_timeout, vn, wait_bit, next_entry_attr, next_entry_vn)

		return
	# NOTE: NOX API hidden behaviour: send a new packet after adding a flow entry
		if buffer_id == None and packet != None:
			for action in actions:
				if action[0] == openflow.OFPAT_OUTPUT:
					self.send_openflow_packet(dp_id, packet, action[1][1], inport)
				else:
					raise NotImplementedError

	def post_callback(self, time, callback):
		self.cnt.postCallback(time, callback)

	def send_desc_stats_request(self, dpid):
		pass

	def send_table_stats_request(self, dpid):
		pass

	def send_port_stats_request(self, dpid, port=-1):
		self.cnt.portStatsRequest(dpid, port)

# X-CHANGE
	def send_flow_command(self, dp_id, command, attrs, priority, add_args, hard_timeout, vn = -1, wait_bit = False, next_entry_attr = {}, next_entry_vn = -1):
		if command == openflow.OFPFC_DELETE_STRICT:
			args = {"attrs": attrs, "priority": priority}
		elif command == openflow.OFPFC_DELETE:
			args = {"attrs": attrs}
		elif command == openflow.OFPFC_MODIFY_STRICT:
			raise NotImplementedError
		elif command == openflow.OFPFC_MODIFY:
			raise NotImplementedError
		elif command == openflow.OFPFC_ADD:
			args = {"attrs": attrs, "priority": priority}
			args["hard_timeout"] = hard_timeout
			args["idle_timeout"] = add_args[0]
			args["actions"] = add_args[1]
			args["buffer_id"] = add_args[2]

		cmd = FlowTableModificationMessage(command, args, vn, wait_bit, next_entry_attr, next_entry_vn)
		#sw = Topology.getSwitchById(dp_id)
		sw = self.cnt.in_connections[dp_id][0]
		sw.enqueueCommand(cmd)

	def delete_strict_datapath_flow(self, dp_id, attrs, priority):
		self.send_flow_command(dp_id, openflow.OFPFC_DELETE_STRICT, attrs, priority, None, 0, vn)

	def __getstate__(self):
		filtered_dict = {}
		return filtered_dict

